Prefix Match
Prefix matching means NGINX matches a request based on the beginning (prefix) of the URI.
If the request URI starts with a given path, that location block is a candidate.
Request URI: /images/logo.png
Prefix: /images/
→ MATCH
This type of match is used for: Static files, Application routes, API paths, Proxies, Almost everything in real-world configs
location /path/ {
...
}
/path/is a literal prefix- Matching is case-sensitive
- No regex involved
Example
server {
listen 80;
server_name example.com;
root /var/www/html;
location /images/ {
root /var/www/assets;
}
}
How This Works
- Request:
/images/logo.png - Matching logic
- Does
/images/logo.pngstart with/images/? → Yes - NGINX selects this location
- Does
- File served:
/var/www/assets/images/logo.png - Because:
root /var/www/assets;
Prefix Matching Priority (Very Important)
NGINX evaluates location blocks in this order:
- Exact match (
location = /path) - Longest prefix match (
location /path/) - Regex match (
location ~) - Default (
location /)
Among prefix matches, the longest matching prefix wins.
location /api/ {
proxy_pass http://backend_api;
}
location /api/v1/ {
proxy_pass http://backend_v1;
}
Requests
| Request | Matched Location |
|---|---|
/api/users | /api/ |
/api/v1/users | /api/v1/ |
The Root (/) Prefix (Catch-All)
location / {
try_files $uri $uri/ =404;
}
/matches everything- Acts as the default location
- Used when no other location matches
Prefix Match with ^~ (Stop Regex Checks)
location ^~ /static/ {
root /var/www/static;
}
- If this prefix matches:
- NGINX skips regex checks
- Improves performance
- Prevents regex from overriding this location
Why ^~ Matters
location ^~ /images/ {
root /var/www/images;
}
location ~ \.jpg$ {
root /var/www/jpg;
}
- Request:
/images/photo.jpg - Result:
- Prefix
/images/matches ^~stops regex- Served from
/var/www/images
- Prefix
Without ^~, the regex location could win.
Prefix Matching vs Exact Matching
location = /login {
return 403;
}
| Request | Matched |
|---|---|
/login | Exact match |
/login/ | Prefix / |
Exact match is higher priority than prefix.
Prefix Matching with alias (Common Pitfall)
location /download/ {
alias /var/files/;
}
- Request:
/download/file.zip - File served:
/var/files/file.zip
With alias, the location path is replaced, not appended.
Common Use Cases for Prefix Locations
- Static files
location /static/ {
root /var/www;
expires 30d;
}
- API routing
location /api/ {
proxy_pass http://api_backend;
}
- Application sections
location /admin/ {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
Common Mistakes
- Forgetting trailing slash (
/pathvs/path/) - Expecting prefix matching to behave like regex
- Misusing
rootvsalias - Not understanding longest prefix wins
- Letting regex override important prefixes